package com.qxzn.module.mine.activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.text.InputFilter;
import android.text.InputType;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.jdsjlzx.recyclerview.LRecyclerView;
import com.github.jdsjlzx.recyclerview.LRecyclerViewAdapter;
import com.qxzn.app.bean.BaseBean;
import com.qxzn.app.bean.FamilyMemberBean;
import com.qxzn.app.page.BaseActivity;
import com.qxzn.app.page.interfaces.MyInterface;
import com.qxzn.app.page.model.MineModel;
import com.qxzn.app.page.view.MyDialog;
import com.qxzn.app.page.widget.ToastUtil;
import com.qxzn.app.util.AppUtil;
import com.qxzn.app.util.CommonUtil;
import com.qxzn.app.util.SharePreferenceUtil;
import com.qxzn.module.mine.R;
import com.qxzn.module.mine.R2;
import com.qxzn.module.mine.adapter.FamilyMemberAdapter;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.ResponseBody;

/**
 * 家庭成员
 */
public class FamilyMemberActivity extends BaseActivity implements MyInterface.GetFamilyMemberListener, MyInterface.AdminDelMemberListener, MyInterface.InvitationMemberListener {
    @BindView(R2.id.lrv)
    LRecyclerView lrv;
    @BindView(R2.id.view_empty)
    View viewEmpty;
    @BindView(R2.id.iv_empty)
    ImageView ivEmpty;
    @BindView(R2.id.tv_empty)
    TextView tvEmpty;
    @BindView(R2.id.tv_add)
    TextView tvAdd;
    @BindView(R2.id.view)
    View view;
    @BindView(R2.id.ll_bottom)
    LinearLayout llBottom;
    @BindView(R2.id.tv_delete)
    TextView tvDelete;

    private LRecyclerViewAdapter recyclerViewAdapter;
    private List<FamilyMemberBean.MemberBean> dataList = new ArrayList();
    private int page = 1;
    private int pageSize = 10;
    private FamilyMemberAdapter adapter;
    private MineModel mineModel;
    private boolean isEdit;
    private String delUserList;
    private MyDialog inputDialog;
    private boolean isAdmin;

    @Override
    protected int initLayout() {
        return R.layout.activity_family_member;
    }

    @Override
    protected void initView() {
        adapter = new FamilyMemberAdapter(this, dataList);
        recyclerViewAdapter = new LRecyclerViewAdapter(adapter);
        lrv.setLayoutManager(new LinearLayoutManager(this));
        lrv.setEmptyView(viewEmpty);
        lrv.setAdapter(recyclerViewAdapter);
        lrv.setPullRefreshEnabled(false);
        lrv.setLoadMoreEnabled(false);
//        lrv.setOnRefreshListener(new OnRefreshListener() {
//            @Override
//            public void onRefresh() {
//                AppUtil.showLog("setOnRefreshListener");
//                page = 1;
//                getData();
//            }
//        });
//        lrv.setOnLoadMoreListener(new OnLoadMoreListener() {
//            @Override
//            public void onLoadMore() {
//                AppUtil.showLog("setOnLoadMoreListener");
//                page++;
//                getData();
//            }
//        });
        viewEmpty.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                lrv.refresh();
            }
        });
        adapter.setItemClick(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                FamilyMemberBean.MemberBean bean = (FamilyMemberBean.MemberBean) v.getTag();
                if (bean != null) {
                    if (isEdit) {
                        if (isAdmin) {
                            if ("1".equals(bean.getAdminstate())) {
                                return;
                            }
                            bean.setCheck(!bean.isCheck());
                            notifyDataSetChanged();
                            boolean isHaveCheck = false;
                            for (FamilyMemberBean.MemberBean memberBean : dataList) {
                                if (memberBean.isCheck()) {
                                    isHaveCheck = true;
                                    break;
                                }
                            }
                            if (isHaveCheck) {
                                tvDelete.setTextColor(getResources().getColor(R.color.red_FD3939));
                            } else {
                                tvDelete.setTextColor(getResources().getColor(R.color.gray_FF999999));
                            }
                        }
                    } else {
                        if (bean.getType() != 3) {
                            AppUtil.showLog("跳转：" + bean.getNiname());
                            startActivity(new Intent(FamilyMemberActivity.this, ShowMemberInfoActivity.class).putExtra("member_bean", bean));
                        }
                    }
                }
            }
        });
        adapter.setViewClick(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                FamilyMemberBean.MemberBean bean = (FamilyMemberBean.MemberBean) v.getTag();
                if (bean != null) {
                    if (isAdmin) {
                        startActivityForResult(new Intent(FamilyMemberActivity.this, ViewToJoinFamilyActivity.class).putExtra("member_bean", bean), 1);
                    }
                }
            }
        });
    }

    @Override
    protected void iniTitleBar() {
        tv_title.setText("家庭成员");
    }

    @Override
    protected void initData(Bundle savedInstanceState) {
        mineModel = new MineModel(this);
        mineModel.setGetFamilyMemberListener(this);
        mineModel.setAdminDelMemberListener(this);
        mineModel.setInvitationMemberListener(this);
        showProgress();
        getData();
    }

    private void getData() {
        JSONObject params = new JSONObject();
        params.put("device_id", SharePreferenceUtil.getDeviceId(this));
        mineModel.getFamilyMember(params);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == 1) {
                getData();
            }
        }
    }

    private void notifyDataSetChanged() {
        adapter.notifyDataSetChanged();
        recyclerViewAdapter.notifyDataSetChanged();
    }

    private void delete() {
        if (isEdit) {
            delUserList = "";
            for (FamilyMemberBean.MemberBean bean : dataList) {
                if (bean.isCheck()) {
                    if (TextUtils.isEmpty(delUserList)) {
                        delUserList += bean.getUsername();
                    } else {
                        delUserList += "," + bean.getUsername();
                    }
                }
            }
            if (TextUtils.isEmpty(delUserList)) {
                tvDelete.setTextColor(getResources().getColor(R.color.red_FD3939));
                isEdit = !isEdit;
                adapter.setEdit(isEdit);
                notifyDataSetChanged();
                this.view.setVisibility(View.VISIBLE);
                tvAdd.setVisibility(View.VISIBLE);
            } else {
                showDialog("确认删除所选成员吗？", "确认删除所选成员吗？", "取消", "删除", null, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        AppUtil.showLog("删除：" + delUserList);
                        showProgress();
                        JSONObject params = new JSONObject();
                        params.put("device_id", SharePreferenceUtil.getDeviceId(FamilyMemberActivity.this));
                        params.put("usernamelist", delUserList);
                        mineModel.adminDelMember(params);
                    }
                });
                dialog.getTvTitle().setVisibility(View.GONE);
                dialog.getTvMessage().setTextSize(18);
            }
        } else {
            tvDelete.setTextColor(getResources().getColor(R.color.gray_FF999999));
            isEdit = !isEdit;
            adapter.setEdit(isEdit);
            notifyDataSetChanged();
            this.view.setVisibility(View.GONE);
            tvAdd.setVisibility(View.GONE);
        }
    }

    protected MyDialog.Builder showInputDialog() {
        MyDialog.Builder builder = new MyDialog.Builder(this).setTitle("输入对方手机号").setPositiveButtonText("邀请")
                .setPositiveButton(new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        String phone = inputDialog.getEtInput().getText().toString().trim();
                        if (!CommonUtil.isMobile(phone)) {
                            AppUtil.showShortToast(FamilyMemberActivity.this, "手机号码不合法，请重新输入");
                            return;
                        }
                        dialog.dismiss();
                        AppUtil.showLog("手机号：" + phone);
                        showProgress();
                        JSONObject params = new JSONObject();
                        params.put("device_id", SharePreferenceUtil.getDeviceId(FamilyMemberActivity.this));
                        params.put("username", phone);
                        mineModel.invitationMember(params);
                    }
                });
        inputDialog = builder.createInputDialog();
        EditText editText = inputDialog.getEtInput();
        editText.setFilters(new InputFilter[]{new InputFilter.LengthFilter(11)});
        editText.setInputType(InputType.TYPE_CLASS_NUMBER);
        inputDialog.setOnShowListener(new DialogInterface.OnShowListener() {
            @Override
            public void onShow(DialogInterface dialog) {
                CommonUtil.showKeyboard(editText);
            }
        });
        inputDialog.show();
        return builder;
    }

    @Override
    protected void onDestroy() {
        if (mineModel != null) {
            mineModel.removeListener();
        }
        if (inputDialog != null) {
            inputDialog.dismiss();
            inputDialog = null;
        }
        super.onDestroy();
    }

    @Override
    public void onGetFamilyMemberSuccess(ResponseBody responseBody) {
        hideProgress();
        HandleFamilyData(responseBody);
    }

    @Override
    public void onGetFamilyMemberFailure() {
        hideProgress();
        AppUtil.showToast(FamilyMemberActivity.this, "网络错误，请稍后再试！");
    }

    private void HandleFamilyData(ResponseBody responseBody) {
        try {
            String json = responseBody.string();
            JSONObject jsonObject = JSONObject.parseObject(json);
            if (jsonObject != null) {
                JSONArray dataArray = jsonObject.getJSONArray("data");
                if (dataArray != null) {
                    dataList.clear();
                    if (dataArray.size() > 0) {
                        JSONObject selfBean = dataArray.getJSONObject(0);
                        if (selfBean != null && selfBean.size() > 0) {
                            FamilyMemberBean.MemberBean bean = JSON.parseObject(selfBean.toJSONString(), FamilyMemberBean.MemberBean.class);
                            if ("1".equals(bean.getAdminstate())) {
                                isAdmin = true;
                                llBottom.setVisibility(View.VISIBLE);
                            } else {
                                isAdmin = false;
                                llBottom.setVisibility(View.GONE);
                            }
                            bean.setType(1);
                            bean.setTitle("家庭成员");
                            dataList.add(bean);
                        }
                    }
                    if (dataArray.size() > 1) {
                        JSONArray authBean = dataArray.getJSONArray(1);
                        if (authBean != null && authBean.size() > 0) {
                            List<FamilyMemberBean.MemberBean> list = JSON.parseArray(authBean.toJSONString(), FamilyMemberBean.MemberBean.class);
                            for (FamilyMemberBean.MemberBean bean : list) {
                                bean.setType(2);
                                dataList.add(bean);
                            }
                        }
                    }
                    if (dataArray.size() > 2) {
                        JSONArray unAuthBean = dataArray.getJSONArray(2);
                        if (unAuthBean != null && unAuthBean.size() > 0) {
                            List<FamilyMemberBean.MemberBean> list = JSON.parseArray(unAuthBean.toJSONString(), FamilyMemberBean.MemberBean.class);
                            for (int i = 0; i < list.size(); i++) {
                                list.get(i).setType(3);
                                if (i == 0) {
                                    list.get(i).setTitle("待加入家庭圈");
                                }
                                dataList.add(list.get(i));
                            }
                        }
                    }
                    tvDelete.setTextColor(getResources().getColor(R.color.red_FD3939));
                    isEdit = false;
                    adapter.setEdit(isEdit);
                    notifyDataSetChanged();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @OnClick({R2.id.tv_delete, R2.id.tv_add})
    public void onViewClicked(View view) {
        int i = view.getId();
        if (i == R.id.tv_delete) {
            delete();
        } else if (i == R.id.tv_add) {
            showInputDialog();
        }
    }

    @Override
    public void onAdminDelMemberSuccess(BaseBean baseBean) {
        hideProgress();
        if (baseBean != null) {
            if (baseBean.getCode() == 200) {
                tvDelete.setTextColor(getResources().getColor(R.color.red_FD3939));
                view.setVisibility(View.VISIBLE);
                tvAdd.setVisibility(View.VISIBLE);
                getData();
                return;
            }
        }
        if (baseBean != null && !TextUtils.isEmpty(baseBean.getMsg())) {
            AppUtil.showToast(this, baseBean.getMsg());
        } else {
            AppUtil.showToast(this, "删除失败，请重试");
        }
    }

    @Override
    public void onAdminDelMemberFailure() {
        hideProgress();
        AppUtil.showToast(FamilyMemberActivity.this, "网络错误，请稍后再试！");
    }

    @Override
    public void onInvitationMemberSuccess(BaseBean baseBean) {
        hideProgress();
        if (baseBean != null) {
            if (baseBean.getCode() == 200) {
                getData();
                ToastUtil.showImgToast(FamilyMemberActivity.this, "已发送", R.mipmap.icon_success);
                return;
            }
        }
        if (baseBean != null && !TextUtils.isEmpty(baseBean.getMsg())) {
            ToastUtil.showImgToast(FamilyMemberActivity.this, baseBean.getMsg(), R.mipmap.icon_failed);
        } else {
            ToastUtil.showImgToast(FamilyMemberActivity.this, "邀请失败，请重试", R.mipmap.icon_failed);
        }
    }

    @Override
    public void onInvitationMemberFailure() {
        hideProgress();
        AppUtil.showToast(FamilyMemberActivity.this, "网络错误，请稍后再试！");
    }
}
